package Controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goShopping/superShopping/superShopping/Models"
	"goShopping/superShopping/superShopping/Utils"
	"goShopping/superShopping/superShopping/cache"
	"net/http"
)

func CreateUser(c *gin.Context){
	var user Models.User
	c.BindJSON(&user)
	err:= Models.CreateUser(&user)
	if err!=nil{
		c.JSON(http.StatusBadGateway,gin.H{"err:":err})
		return
	}else{
		c.JSON(http.StatusOK,nil)
	}
}

func Login(c *gin.Context){
	username:=c.Query("username")
	password:=c.Query("password")
	user,err:= Models.LoginUser(username)
	if err==nil&&user[0].Password==password{
		//生成token
		token,err:= Utils.GenToken(username,password)
		if err!=nil{
			fmt.Println(err)
			c.JSON(http.StatusOK,gin.H{
				"code":-1,
				"message":err,
				"msg":"生成token失败",
			})
			return
		}
		c.JSON(http.StatusOK,gin.H{
			"code":0,
			"msg":"成功",
			"data":gin.H{
				"msg":user,
				"token":token,
			},
		})
	}else{
		c.JSON(http.StatusOK,gin.H{
			"code":-1,
			"message":"用户名或密码错误",
		})
		return
	}
}

func UserListController(ctx *gin.Context) {
	user,err:= Models.OrUser()
	if err!=nil{
		ctx.JSON(http.StatusOK,gin.H{
			"code":-1,
			"msg":"获取失败",
			"error":err,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 1,
		"msg":  "成功",
		"data": user,
	})
}

func GetUserByPwd(c *gin.Context){
	username:=c.Query("username")
	a,err:=cache.GetKey(username)
	if err!=nil{
		user,err:=Models.LoginUser(username)
		if err!=nil{
			c.JSON(http.StatusOK,gin.H{"msg":err,"code":-1})
			return
		}
		errSet:=cache.SetKey(username,user)
		if errSet!=nil{
			c.JSON(http.StatusOK,gin.H{"msg":errSet,"code":-1})
			return
		}
		c.JSON(http.StatusOK,gin.H{"msg":user,"code":1})
	}else{
			c.JSON(http.StatusOK,gin.H{"msg":a,"code":1})
			return
	}
}




